package com.chaodev.base.config;

import cn.hutool.core.util.StrUtil;
import com.chaodev.base.base.RedisDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter
/**
 * 用户不操作一定时间后清除TOKEN
 */
public class ExpireCheckFilter extends OncePerRequestFilter {
    @Autowired
    private RedisDao redisDao;
    @Value("${variables.noHandleExpireTime}")
    private long noHandleTime;
    @Value("${variables.tokenExpireTime}")
    private long expireTime;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token=request.getHeader("token");
        if(!StrUtil.isEmpty(token)&&!"false".equals(token)){
            Object timeObj=redisDao.vGet("expt"+token);
            if(timeObj!=null){
                long lastHandleTime=(long)timeObj;
                long now= System.currentTimeMillis();
                //大于配置的时间直接清空用户信息
                if(now-lastHandleTime>noHandleTime*1000){
                    redisDao.delete(token);
                    redisDao.delete("expt"+token);
                }
                else{
                    redisDao.vSet("expt"+token,now,expireTime);
                }
            }

        }
//        while(request.getHeaderNames().hasMoreElements()){
//            String ss=request.getHeaderNames().nextElement();
//        }
//        long lastHandleTime=(long)redisDao.vGet("expt"+token);
        super.doFilter(request,response,filterChain);
    }
}
